package com.laisheng.interview.service.impl;

import com.laisheng.interview.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;

/**
 * 邮件服务实现类
 */
@Slf4j
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public boolean sendSimpleMail(String to, String subject, String content) {
        try {
            log.info("开始发送邮件，收件人: {}, 主题: {}, 发件人: {}", to, subject, from);
            
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom(from);
            message.setTo(to);
            message.setSubject(subject);
            message.setText(content);
            
            log.info("邮件消息已创建，准备发送...");
            mailSender.send(message);
            log.info("简单邮件发送成功，收件人: {}", to);
            return true;
        } catch (Exception e) {
            log.error("简单邮件发送失败，收件人: {}, 主题: {}, 错误: {}", to, subject, e.getMessage(), e);
            return false;
        }
    }

    @Override
    public boolean sendHtmlMail(String to, String subject, String htmlContent) {
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);
            
            mailSender.send(message);
            log.info("HTML邮件发送成功，收件人: {}", to);
            return true;
        } catch (MessagingException e) {
            log.error("HTML邮件发送失败，收件人: {}, 错误: {}", to, e.getMessage(), e);
            return false;
        }
    }
} 